
//
//  IMAPIConfig.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/6/23.
//

#import "IMAPIConfig.h"
#import "IMDeviceUtils.h"
#import "IMLogUtils.h"

// 通用域名配置常量
static NSString *kBaseProUrl = @"https://sapi.yarkgame.com";       // 正式环境域名

// 内购支付域名不再单独维护，复用当前基础域名

@implementation IMAPIConfig

static IMAPIConfig *_sharedConfig = nil;
static dispatch_once_t _onceToken;

+ (instancetype)sharedConfig {
    dispatch_once(&_onceToken, ^{
        _sharedConfig = [[IMAPIConfig alloc] init];
    });
    return _sharedConfig;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupDefaultConfiguration];
    }
    return self;
}

- (void)setupDefaultConfiguration {
    // 域名配置 - 使用内购相关的域名
    _baseURL = kBaseProUrl;     // 正式环境域名
    _isDebugMode = NO;
    
    // 请求配置
    _defaultTimeoutInterval = 30.0;
    _defaultRetryCount = 2;
    _retryInterval = 1.0;
    
    // SDK版本信息
    _sdkVersion = @"1.0.0";
    _appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: @"1.0.0";
    
    // 默认请求头
    _defaultHeaders = @{
        @"Content-Type": @"application/json",
        @"Accept": @"application/json",
        @"X-SDK-Version": _sdkVersion,
        @"X-Platform": @"iOS"
    };
    
#ifdef DEBUG
    _isDebugMode = YES;
    // 未默认配置测试域名，若未外部指定测试域名则回退到正式域名
    NSString *effectiveURL = [self currentBaseURL];
    [IMLogUtils info:IMLogTagGeneral format:@"🔧 API配置初始化 - DEBUG环境，当前域名: %@", effectiveURL];
#else
    [IMLogUtils info:IMLogTagGeneral format:@"🔧 API配置初始化 - RELEASE环境，使用正式域名: %@", _baseURL];
#endif
    
    [IMLogUtils info:IMLogTagGeneral format:@"📡 当前激活域名: %@", [self currentBaseURL]];
    [IMLogUtils info:IMLogTagIAP format:@"💰 当前内购支付域名: %@", [self inAppPurchaseBaseURL]];
}

#pragma mark - Properties

- (NSString *)currentBaseURL {
    if (_isDebugMode) {
        return (_debugBaseURL && _debugBaseURL.length > 0) ? _debugBaseURL : _baseURL;
    }
    return _baseURL;
}

- (NSString *)inAppPurchaseBaseURL {
    // IAP 域名与当前基础域名保持一致
    return [self currentBaseURL];
}

- (NSString *)loginEndpoint {
    return @"/api/wsdk/login";
}

#pragma mark - Configuration Methods

- (void)configureProductionWithBaseURL:(NSString *)baseURL appID:(NSString *)appID {
    _baseURL = [baseURL copy];
    _appID = [appID copy];
    
    NSMutableDictionary *headers = [_defaultHeaders mutableCopy];
    if (appID) {
        headers[@"X-App-ID"] = appID;
    }
    _defaultHeaders = [headers copy];
}

- (void)configureDebugWithBaseURL:(NSString *)debugBaseURL appID:(NSString *)appID {
    _debugBaseURL = [debugBaseURL copy];
    _appID = [appID copy];
    
    NSMutableDictionary *headers = [_defaultHeaders mutableCopy];
    if (appID) {
        headers[@"X-App-ID"] = appID;
    }
    _defaultHeaders = [headers copy];
}

- (void)switchToProduction {
    _isDebugMode = NO;
}

- (void)switchToDebug {
    _isDebugMode = YES;
}

@end
